package com.folioreader.ui.view;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.appbar.AppBarLayout;

public class FolioAppBarLayoutNew extends AppBarLayout {

    int navigationBarHeight= 0;
    Rect insetsRect= null;

    public int getNavigationBarHeight() {
        return navigationBarHeight;
    }

    public Rect getInsetsRect() {
        return insetsRect;
    }

    public FolioAppBarLayoutNew(Context context) {
        super(context);
    }

    public FolioAppBarLayoutNew(Context context, AttributeSet attrs) {
        super(context, attrs);
        ViewCompat.setOnApplyWindowInsetsListener(this, new androidx.core.view.OnApplyWindowInsetsListener() {
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                insetsRect = new Rect(
                        insets.getSystemWindowInsetLeft(),
                        insets.getSystemWindowInsetTop(),
                        insets.getSystemWindowInsetRight(),
                        insets.getSystemWindowInsetBottom()
                );

                navigationBarHeight= insets.getSystemWindowInsetBottom();
                setMargins(
                        insets.getSystemWindowInsetLeft(),
                        insets.getSystemWindowInsetTop(),
                        insets.getSystemWindowInsetRight());

                return insets;
            }
        });
    }

    @Override
    protected boolean fitSystemWindows(Rect insets) {
        this.insetsRect = new Rect(insets);
        navigationBarHeight= insets.bottom;
        setMargins(insets.left, insets.top, insets.right);
        return super.fitSystemWindows(insets);
    }
    private void setMargins(int left, int top, int right){
        MarginLayoutParams marginLayoutParams = (MarginLayoutParams) getLayoutParams();
        marginLayoutParams.leftMargin= left;
        marginLayoutParams.topMargin = top;
        marginLayoutParams.rightMargin = right;
        setLayoutParams(marginLayoutParams);
    }
    public void setTopMargin(int top){
        MarginLayoutParams marginLayoutParams = (MarginLayoutParams) getLayoutParams();
        marginLayoutParams.topMargin = top;
        setLayoutParams(marginLayoutParams);
    }
}
